from datetime import datetime
import json,sys,psutil,pyautogui
import os,time,schedule,datetime
import pandas as pd
import webbrowser,cv2,pyscreeze
import requests

def send_wechat_msg(content):
    webhook_url= "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=b20915c0-1822-485c-8a69-ee0a9f594014"
    data = {"msgtype": "text",
    "mentioned_list":["张文强"],
    "text": {"content": content}}
    proxies = {
        "http": None,
        "https": None,
    }
    header = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.40 Safari/537.36 Edg/87.0.664.24'
    }
    requests.packages.urllib3.disable_warnings()
    r = requests.post(url=webhook_url,headers=header, data=json.dumps(data, ensure_ascii=False).encode('utf-8'), verify=False,proxies=proxies)
    return r.text, r.status_code

def getButton(targetImage):
    # 屏幕缩放系数 mac缩放是2 windows一般是1
    screenScale = 1
    # 事先读取按钮截图
    target = cv2.imread(targetImage, cv2.IMREAD_GRAYSCALE)
    # 先截图
    screenshot = pyscreeze.screenshot('my_screenshot.png')
    # 读取图片 灰色会快
    temp = cv2.imread(r'my_screenshot.png', cv2.IMREAD_GRAYSCALE)
    theight, twidth = target.shape[:2]
    tempheight, tempwidth = temp.shape[:2]
    # 先缩放屏幕截图 INTER_LINEAR INTER_AREA
    scaleTemp = cv2.resize(temp, (int(tempwidth / screenScale), int(tempheight / screenScale)))
    stempheight, stempwidth = scaleTemp.shape[:2]
    # 匹配图片
    res = cv2.matchTemplate(scaleTemp, target, cv2.TM_CCOEFF_NORMED)
    mn_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
    if (max_val >= 0.9):
        # 计算出中心点
        top_left = max_loc
        bottom_right = (top_left[0] + twidth, top_left[1] + theight)
        tagHalfW = int(twidth / 2)
        tagHalfH = int(theight / 2)
        tagCenterX = top_left[0] + tagHalfW
        tagCenterY = top_left[1] + tagHalfH
        # 左键点击屏幕上的这个位置
        pyautogui.click(tagCenterX, tagCenterY, button='left')
    else:
        print("没找到")

def 可转债通知():
    print(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")+"执行任务：可转债通知")
    send_wechat_msg(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")+"执行任务：可转债通知")
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36",
    }
    newUrl ="https://www.jisilu.cn/data/cbnew/pre_list/?___jsl=LST___t=1584777951900"
    #最简单的爬虫请求.也可以加上headers字段，防止部分网址的反爬虫机制
    response = requests.get(newUrl)
    #当爬取的界面需要用户名密码登录时候，构建的请求需要包含auth字段
    data = response.content.decode("utf-8")
    dat = json.loads(data)
    #print(dat['rows'][0])
    # 所有数据
    lst_data = []
    for one in dat['rows']:
        # 每一条数据
        lst_dat = []
        # 转债id
        id = one["id"]
        dat_cell = one["cell"]
        # 是否赎回
        is_shui =  dat_cell['apply_date']
        if is_shui != None:
            #上市转债代码
            Bid = dat_cell['bond_id']
            # 转债名称
            name = dat_cell['bond_nm']
            # 申购日期
            apply_date = dat_cell['apply_date']
            # 申购代码
            apply_cd = dat_cell['apply_cd']
            # 上市日期
            list_date = dat_cell['list_date']
            lst_dat.append(id)
            lst_dat.append(Bid)
            lst_dat.append(name)
            lst_dat.append(apply_date)
            lst_dat.append(list_date)
            lst_data.append(lst_dat)
        else:
            continue
    for bond in  lst_data:
        today = datetime.date.today()
        tomorrow = str(today + datetime.timedelta(days=1))
        # 判断是否明天是否有申购的新债
        if bond[3]==tomorrow:
            send_wechat_msg(f"【新债申购】明天有可申购的新债:{bond[2]}")
        # 判断是否明天是否有上市的新债
        elif bond[4]==tomorrow:
            dealBondPath=os.path.join(sys.path[0],"dealBond.csv")
            dealBond=pd.read_csv(dealBondPath)
            dealList=dealBond["中签代码"].tolist()
            if int(bond[1]) in dealList:
                accountDeal=dealBond[dealBond["中签代码"]==int(bond[1])]["中签人"].tolist()
                send_wechat_msg(f"【新债上市】明天有可上市的中签新债:{bond[2]}，中签人：{accountDeal}")

def 打开微信读书():
    print(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")+"执行任务：打开微信读书")
    send_wechat_msg(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")+"执行任务：打开微信读书")
    for proc in psutil.process_iter():
        try:
            if proc.name() == "wereader.exe":
                os.system(r'taskkill /F /IM {}'.format("wereader.exe"))
        except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
            pass
    weixinPath=r"C:\Users\Administrator\AppData\Local\Programs\wereader"
    os.startfile(os.path.join(weixinPath,"wereader.exe"))
    time.sleep(10)
    pyautogui.press('tab')
    pyautogui.press('enter')
    time.sleep(60*60)    # 休眠1个小时，杀掉进程
    for proc in psutil.process_iter():
        try:
            if proc.name() == "wereader.exe":
                os.system(r'taskkill /F /IM {}'.format("wereader.exe"))
        except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
            pass

def 知鸟():
    print(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") + "执行任务：播放知鸟视频")
    send_wechat_msg(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")+"执行任务：播放知鸟视频")
    知鸟任务列表=pd.read_excel(os.path.join(sys.path[0],"知鸟.xls"))
    for index,row in 知鸟任务列表.iterrows():
        知鸟任务列表New = pd.read_excel(os.path.join(sys.path[0], "知鸟.xls"))
        if 知鸟任务列表New.loc[index,"完成"]!="Y" and 知鸟任务列表New.loc[index,"日期"]==datetime.date.today():
            webbrowser.open(知鸟任务列表New.loc[index,"地址"])
            time.sleep(10)
            print("开始播放视频")
            getButton(os.path.join(sys.path[0], "2-1.png"))
            等待时间片=int((知鸟任务列表New.loc[index,"时长"]*60+180)/180)
            for i in range(等待时间片):
                pyautogui.scroll(100)
                time.sleep(180)
            #超过视频时间，更新视频状态为已完成
            知鸟任务列表New.loc[index,"完成"]="Y"
            播放时长=知鸟任务列表New.loc[index,"时长"]
            send_wechat_msg(f"已自动播放知鸟视频{播放时长}分钟")
            # 知鸟任务列表New.rename(columns={"地址","时长","完成","日期"})
            知鸟任务列表New.to_excel(os.path.join(sys.path[0],"知鸟.xls"),index=False)

def func():
    # 清空任务
    schedule.clear()
    oneDay=10*60*24    #24小时
    # 每天执行一次可转债通知
    schedule.every(oneDay).seconds.do(可转债通知)
    # 每天执行一次微信读书
    schedule.every(oneDay).seconds.do(打开微信读书)
    #每天执行一次知鸟
    #schedule.every(oneDay).seconds.do(知鸟)
    while True:
        schedule.run_pending()
func()



